import json

from django.shortcuts import render
from top_app import models
from django.core import serializers
from django.shortcuts import HttpResponse
from movie_app import views as movieview
# Create your views here.

#检索数据库中排行榜数据的数据
#type 1 :国产 2:欧美 3:其他地区 4:全球总榜单
def top_search(type=1):
    if type == 1:
        all = models.top_info.objects.filter(place=1).order_by('rank')
    elif type == 2:
        all = models.top_info.objects.filter(place=2).order_by('rank')
    elif type == 3:
        all = models.top_info.objects.filter(place=3).order_by('rank')
    elif type == 4:
        all = models.top_info.objects.filter(place=4).order_by('rank')
    else:
        return []
    json_data = serializers.serialize('python',all) #序列化查询出的数据,转成json数据
    list = []                                       #将json数据转化成list
    for line in json_data:
        msg = line['fields']   #每一条信息
        #处理时间数据
        time_data = str(msg['showtime'])[:10]
        linelist = [msg['rank'],msg['imgurl'],msg['name'],msg['mainact'],time_data,msg['score']]#提取主要信息
        linelist.append(type)
        list.append(linelist)
    return list

#返回模板
def index(request):
    return render(request,'top.html')
#tab数据返回
def showtab(request):
    keys = ['rank','imagsrc','name','mainact','time','score','type']
    listall = [[],[],[],[]]
    for j in range(4):
        listall[j] = top_search(j+1)
        for i in range(10):
            listall[j][i] = dict(zip(keys,listall[j][i]))
    #listall 二维字典列表
    keys2 = ['1','2','3','4','5','6','7','8','9','10']   #第二层
    keys3 = ['pag1','pag2','pag3','pag4']  #第三层
    dictall = {}
    for x in range(4):
        lista = dict(zip(keys2,listall[x]))
        dica = {keys3[x]:lista}
        dictall.update(dica)
    #dictall 所有数据三层字典
    result = json.dumps(dictall,ensure_ascii=False)
    return HttpResponse(result)

#电影详情返回
def showdetail(request,name,time):
    return movieview.tomovieall(request,name,time)
